package com.vanke.kotlin_mvp.addedit

import com.vanke.kotlin_mvp.data.Task
import com.vanke.kotlin_mvp.data.TaskDataSource
import com.vanke.kotlin_mvp.data.TaskRepository

/**
 * @name Kotlin_MVP
 * @package name：com.vanke.kotlin_mvp.addedit
 * @class describe
 * @anthor shiyuchuan
 * @time 2017/8/22 16:52
 */
class AddEditTaskPresenter(private val taskId: String?,
                           val taskRepository: TaskRepository,
                           val addTaskView: AddEditTaskContract.View,
                           override var isDataMissing: Boolean) : AddEditTaskContract.Presenter, TaskDataSource.GetTaskCallback {
    override fun onTaskLoaded(task: Task) {
        if (addTaskView.isActive) {
            addTaskView.setTitle(task.title)
            addTaskView.setDescription(task.description)
        }
        isDataMissing = false
    }

    override fun onDataAvailable() {
        if (addTaskView.isActive) {
            addTaskView.showEmptyTaskError()
        }
    }

    init {
        addTaskView.presenter = this
    }

    override fun start() {
        if (taskId != null && isDataMissing) {
            populateTask()
        }
    }

    override fun saveTask(title: String, description: String) {
        if (taskId == null) {
            createTask(title, description)
        } else {
            updateTask(title, description)
        }
    }

    private fun updateTask(title: String, description: String) {
        if (taskId == null) {
            throw RuntimeException()
        }
        taskRepository.saveTask(Task(title, description, taskId))
        addTaskView.showTasksList()
    }

    private fun createTask(title: String, description: String) {
        val newTask = Task(title, description)
        if (newTask.isEmpty) {
            addTaskView.showEmptyTaskError()
        } else {
            taskRepository.saveTask(newTask)
            addTaskView.showTasksList()
        }
    }

    override fun populateTask() {
        if (taskId == null) {
            throw RuntimeException()
        }
        taskRepository.getTask(taskId, this)
    }


}